package cn.icyzx.filter;

import cn.icyzx.exception.TipException;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author zk
 * @Date 2017/4/29.
 * @Email 2117251154@qq.com
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

    /**
     * 用来处理所有TipExcetion类，以友好的方式返回错误信息并记录
     *
     * @param request
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler(TipException.class)
    @ResponseBody
    public String tipExcetpionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        logger.info(ex.getMessage());
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return ex.getMessage();
    }

}
